package com.msf.tutorial.java8.chapter1;

import com.msf.tutorial.java8.Apple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 终极状态：使用泛型，实现通用 Filter
 */
public class Step6 {

    interface Filter<T> {
        boolean test(T apple);
    }

    /**
     * 通用filter方法
     */
    public static <T> List<T> filter(List<T> inventory, Filter<T> filter) {
        List<T> result = new ArrayList<>();
        for (T item: inventory) {
            if ( filter.test(item) ) {
                result.add(item);
            }
        }
        return result;
    }

    public static void main(String[] args) {

        List<Apple> list = Arrays.asList(
            new Apple(1L, "red", 1D),
            new Apple(2L, "red", 2D),
            new Apple(3L, "green", null),
            new Apple(1L, "green", 3D)
        );

        List<Apple> greenApples = filter(list, apple -> "green".equals(apple));
        List<Apple> redApples = filter(list, apple -> "red".equals(apple));

        System.out.println(greenApples);
        System.out.println(redApples);

        List<Integer> intList = Arrays.asList(1,2,3,4);
        List<Integer> evenNumbers = filter(intList, i -> i % 2 == 0);

        System.out.println(evenNumbers);
    }

}
